﻿using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Linq;

namespace ST.Buz.Service
{
	public partial interface IServiceSysEnumCode
	{
		#region 树相关
		/// <summary>
		/// 获取指定及其所有下级的树节点数据
		/// </summary>
		/// <returns></returns>
		List<TreeItem> GetTreeDataByID(string code, int? id, UserSession sessionCurrent);

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的简单格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		List<SimpleTreeItem> GetSimpleTreeDataByID(string code, int? id, UserSession sessionCurrent);

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的ZTree格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		List<ZTreeItem> GetZTreeDataByID(string code, int? id, UserSession sessionCurrent);

		/// <summary>
		/// 获取指定及其所有下级的树节点数据
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		List<Sys_EnumCode> GetDataByPID(int? pID, string pCode, int orgID, UserSession sessionCurrent);

		/// <summary>
		/// 获取自身及所有下级节点ID
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		List<int> GetChildren(int id);

		/// <summary>
		/// 修改父节点
		/// </summary>
		bool UpdateParent(int id, int parentID, UserSession sessionCurrent);

		/// <summary>
		/// 修改排序
		/// </summary>
		bool UpdateOrder(SortItem[] items, UserSession sessionCurrent);
		#endregion

		/// <summary>
		/// 分页列表
		/// </summary>
		PageData GetPageList(VMS_Sys_EnumCode searchModel);

		/// <summary>
		/// 批量获取根节点信息
		/// </summary>
		/// <returns></returns>
		List<SelectListItem> GetRootList(UserSession sessionCurrent, EnumCodeOptionValueType optionValueType = EnumCodeOptionValueType.Name);

		/// <summary>
		/// 获取指定编号的下级节点
		/// </summary>
		/// <param name="parentCode"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		List<SelectListItem> GetChildrenList(string parentCode, string selected, UserSession sessionCurrent, EnumCodeOptionValueType optionValueType = EnumCodeOptionValueType.Name);

		/// <summary>
		/// 批量获取信息
		/// </summary>
		/// <returns></returns>
		List<Sys_EnumCode> GetList(string[] codes, UserSession sessionCurrent);

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		List<Sys_EnumCode> GetList(string code, UserSession sessionCurrent);

		Sys_EnumCode GetByCode(string code, UserSession sessionCurrent);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="code"></param>
		/// <param name="name"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		Sys_EnumCode EnsureCodeValid(string code, string name, UserSession sessionCurrent);

		/// <summary>
		/// 新增或修改信息
		/// </summary>
		int AddOrUpdate(Sys_EnumCode model, UserSession sessionCurrent);

		/// <summary>
		/// 批量更新
		/// </summary>
		/// <param name="models"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool BatchUpdate(IEnumerable<Sys_EnumCode> models, UserSession sessionCurrent);

		/// <summary>
		/// 删除部门
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool Delete(int id, UserSession sessionCurrent);

		/// <summary>
		/// 根据id获取详细信息
		/// </summary>
		Sys_EnumCode GetEditDetail(int id, UserSession sessionCurrent);

		/// <summary>
		/// 根据id获取详细信息
		/// </summary>
		Sys_EnumCode GetViewDetail(int id, UserSession sessionCurrent);
	}

	public partial class ServiceSysEnumCode
	{
		private readonly IServiceSysLog serviceSysLog;

		public ServiceSysEnumCode(BuzContext ctx,
			IServiceSysLog _serviceSysLog,
			ILogger<ServiceSysEnumCode> log)
		{
			serviceSysLog = _serviceSysLog;
			context = ctx;
			logger = log;
		}

		#region 树相关
		/// <summary>
		/// 获取指定及其所有下级的树节点数据
		/// </summary>
		/// <returns></returns>
		public List<TreeItem> GetTreeDataByID(string code, int? id, UserSession sessionCurrent)
		{
			throw new NotImplementedException();
		}

		public List<Sys_EnumCode> GetDataByPID(int? pID, string pCode, int orgID, UserSession sessionCurrent)
		{
			SqlParameter[] parameters = new SqlParameter[]{
					new SqlParameter("@code",System.Data.SqlDbType.VarChar,32),
					new SqlParameter("@orgid",System.Data.SqlDbType.Int),
					new SqlParameter("@id", System.Data.SqlDbType.Int),
					new SqlParameter("@errcode",System.Data.SqlDbType.Int),
					new SqlParameter("@errmsg",System.Data.SqlDbType.NVarChar,200)
				};
			parameters[0].Value = pCode;
			parameters[1].Value = orgID;
			if (pID.HasValue && pID.Value > 0)
			{
				parameters[2].Value = pID;
			}
			else
			{
				parameters[2].Value = DBNull.Value;
			}
			parameters[parameters.Length - 2].Direction = System.Data.ParameterDirection.Output;
			parameters[parameters.Length - 1].Direction = System.Data.ParameterDirection.Output;
			var result = context.SysEnumCode.FromSqlRaw("sp_sys_enumcode_tree @code,@orgid,@id,@errcode output,@errmsg output", parameters).ToList();
			if ((int)parameters[parameters.Length - 2].Value != 0)
			{
				throw new BuzException(Convert.ToString(parameters[parameters.Length - 1].Value));
			}
			return result;
		}

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的简单格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public List<SimpleTreeItem> GetSimpleTreeDataByID(string code, int? id, UserSession sessionCurrent)
		{
			try
			{
				//var query = from m in context.SysEnumCode
				//			select new SimpleTreeItem()
				//			{
				//				pId = m.PID.ToString(),
				//				id = m.ID.ToString(),
				//				key = m.ID.ToString(),
				//				value = m.ID.ToString(),
				//				title = m.Name,
				//			};
				//return query.ToList();
				var treeData = GetDataByPID(id, code, sessionCurrent.OrgID, sessionCurrent);
				var result = new List<SimpleTreeItem>();
				foreach (var q in treeData)
				{
					result.Add(new SimpleTreeItem()
					{
						pId = q.PID.ToString(),
						id = q.ID.ToString(),
						key = q.ID.ToString(),
						value = q.ID.ToString(),
						title = q.Name,
					});
				}
				return result;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException(ex.Message, ex);
			}
		}

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的ZTree格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public List<ZTreeItem> GetZTreeDataByID(string code, int? id, UserSession sessionCurrent)
		{
			try
			{
				var result = new List<ZTreeItem>();
				var treeData = GetDataByPID(id, code, sessionCurrent.OrgID, sessionCurrent);
				if (treeData == null || treeData.Count == 0)
				{
					result.Add(new ZTreeItem()
					{
						id = "0",
						pId = "-1",
						name = "暂无结果",
						isParent = true,
						open = true,
						noClick = true
					});
					return result;
				}
				foreach (var q in treeData)
				{
					result.Add(new ZTreeItem()
					{
						pId = q.PID.ToString(),
						id = q.ID.ToString(),
						name = q.Name,
						isParent = q.Children > 0,
						open = true,
						noClick = q.PID == 0
					});
				}
				return result;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException(ex.Message, ex);
			}
		}

		/// <summary>
		/// 获取自身及所有下级节点ID
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public List<int> GetChildren(int id)
		{
			if (id <= 0)
			{
				return null;
			}
			try
			{
				var children = context.ExecuteReader<TreeIdentity>(
						"sp_sys_get_tree_children",
						new SqlParameter[] { new SqlParameter("@id", id), new SqlParameter("@table_name", "Sys_EnumCode") }
					);
				if (children.Count == 0)
				{
					return null;
				}
				List<int> lstTree = new List<int>();
				foreach (var c in children)
				{
					lstTree.Add(c.ID);
				}
				return lstTree;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取下级节点出错");
				throw new BuzException("获取下级节点失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 修改父节点
		/// </summary>
		public bool UpdateParent(int id, int parentID, UserSession sessionCurrent)
		{
			try
			{
				if (id <= 0)
				{
					throw new BuzException("参数不能为空");
				}
				var modelOld = context.SysEnumCode.SingleOrDefault(m => m.ID == id);
				if (modelOld == null)
				{
					throw new BuzException("未找到相关记录");
				}
				if (parentID > 0)
				{
					List<int> lstChildren = GetChildren(id);
					if (lstChildren == null || lstChildren.Contains(parentID))
					{
						throw new BuzException("上级不存在或上级选择有误");
					}
				}
				modelOld.PID = parentID;
				context.SaveChanges();

				return true;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException(ex.Message, ex);
			}
		}

		/// <summary>
		/// 修改排序
		/// </summary>
		public bool UpdateOrder(SortItem[] items, UserSession sessionCurrent)
		{
			try
			{
				if (items == null || items.Length == 0)
				{
					throw new BuzException("参数不能为空");
				}
				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						foreach (SortItem item in items)
						{
							var entity = context.SysEnumCode.Attach(new Sys_EnumCode()
							{
								ID = item.id,
								Sort = item.order
							});
							entity.Property("Sort").IsModified = true;
							context.SaveChanges();
						}
						trans.Commit();

						return true;
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "更新出错");
				throw ex;
			}
			catch (DbUpdateException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "更新出错");
				throw new BuzException("更新失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "更新出错");
				throw new BuzException("更新失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}
		#endregion

		/// <summary>
		/// 批量获取根节点信息
		/// </summary>
		/// <returns></returns>
		public List<SelectListItem> GetRootList(UserSession sessionCurrent, EnumCodeOptionValueType optionValueType = EnumCodeOptionValueType.Name)
		{
			try
			{
				var list = context.SysEnumCode.Where(m => m.PID == 0).OrderBy(m => m.Sort).ThenBy(m => m.ID).AsNoTracking().ToList();
				List<SelectListItem> results = new List<SelectListItem>();
				switch (optionValueType)
				{
					case EnumCodeOptionValueType.ID:
						foreach (var item in list)
						{
							results.Add(new SelectListItem()
							{
								Text = item.Name,
								Value = item.ID.ToString()
							});
						}
						break;
					case EnumCodeOptionValueType.Name:
						foreach (var item in list)
						{
							results.Add(new SelectListItem()
							{
								Text = item.Name,
								Value = item.Name
							});
						}
						break;
					case EnumCodeOptionValueType.Value:
						foreach (var item in list)
						{
							results.Add(new SelectListItem()
							{
								Text = item.Name,
								Value = item.Value
							});
						}
						break;
				}
				return results;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		public List<SelectListItem> GetChildrenList(string parentCode, string selected, UserSession sessionCurrent, EnumCodeOptionValueType optionValueType = EnumCodeOptionValueType.Name)
		{
			try
			{
				List<SelectListItem> results = new List<SelectListItem>();
				var list = (from c in context.SysEnumCode
							join p in context.SysEnumCode on c.PID equals p.ID
							where p.Code == parentCode && p.PID == 0
							orderby c.Sort, c.ID
							select c).AsNoTracking().ToList();
				switch (optionValueType)
				{
					case EnumCodeOptionValueType.ID:
						foreach (var item in list)
						{
							results.Add(new SelectListItem()
							{
								Text = item.Name,
								Value = item.ID.ToString()
							});
						}
						break;
					case EnumCodeOptionValueType.Name:
						foreach (var item in list)
						{
							results.Add(new SelectListItem()
							{
								Text = item.Name,
								Value = item.Name
							});
						}
						break;
					case EnumCodeOptionValueType.Value:
						foreach (var item in list)
						{
							results.Add(new SelectListItem()
							{
								Text = item.Name,
								Value = item.Value
							});
						}
						break;
				}

				if (!string.IsNullOrEmpty(selected) && results != null && results.Count > 0)
				{
					foreach (var item in results)
					{
						if (item.Value == selected)
						{
							item.Selected = true;
						}
					}
				}
				return results;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 批量获取信息
		/// </summary>
		/// <returns></returns>
		public List<Sys_EnumCode> GetList(string[] codes, UserSession sessionCurrent)
		{
			try
			{
				if (codes == null || codes.Length == 0)
				{
					throw new BuzException("参数不能为空");
				}
				return context.SysEnumCode.Where(m => codes.Contains(m.Code)).OrderBy(m => m.Sort).ThenBy(m => m.ID).AsNoTracking().ToList();
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		public List<Sys_EnumCode> GetList(string code, UserSession sessionCurrent)
		{
			try
			{
				if (string.IsNullOrEmpty(code))
				{
					throw new BuzException("参数不能为空");
				}
				return context.SysEnumCode.Where(m => m.Code == code).OrderBy(m => m.Sort).ThenBy(m => m.ID).AsNoTracking().ToList();
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		public Sys_EnumCode GetByCode(string code, UserSession sessionCurrent)
		{
			try
			{
				if (string.IsNullOrEmpty(code))
				{
					throw new BuzException("参数不能为空");
				}
				return context.SysEnumCode.Where(m => m.Code == code).FirstOrDefault();
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_Sys_EnumCode searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();

				var query = from u in context.SysEnumCode
							join p in context.SysEnumCode on u.PID equals p.ID into uptmp
							from up in uptmp.DefaultIfEmpty()
							select new
							{
								u.ID,
								u.PID,
								u.Name,
								Value = u.Value,
								PName = up.Name,
								u.Code,
								u.Comment,
								u.Sort,
								u.Reserved,
								u.AddDate,
								u.AddManID,
								u.AddManName,
								u.OrgID,
							};
				if (!string.IsNullOrWhiteSpace(searchModel.name))
				{
					query = query.Where(m => EF.Functions.Like(m.Name, "%" + searchModel.name + "%"));
				}
				if (!string.IsNullOrEmpty(searchModel.value))
				{
					query = query.Where(m => EF.Functions.Like(m.Value, "%" + searchModel.value + "%"));
				}
				if (searchModel.ids != null && searchModel.ids.Length > 0)
				{
					query = query.Where(m => searchModel.ids.Contains(m.ID));
				}
				if (searchModel.pid.HasValue && searchModel.pid > 0)
				{
					query = query.Where(m => m.PID == searchModel.pid.Value);
				}
				else if (!string.IsNullOrEmpty(searchModel.pname))
				{
					query = query.Where(m => m.PName == searchModel.pname);
				}
				else
				{
					query = query.Where(m => m.PID != 0);//过滤根级别的项目
				}

				switch (searchModel.sortby)
				{
					case "Code":
						////数据库分页，不支持多表
						//query = query.OrderByDescending(e => EF.Property<object>(e, sortOrder));
						////内存分页
						////query = query.OrderByDescending(e => e.GetType().GetProperty(sortOrder).GetValue(e, null));
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Code) : query.OrderByDescending(e => e.Code);
						break;
					case "Name":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name);
						break;
					case "Reserved":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Reserved) : query.OrderByDescending(e => e.Reserved);
						break;
					case "Sort":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Sort) : query.OrderByDescending(e => e.Sort);
						break;
					default:
						query = query.OrderBy(e => e.Sort).ThenBy(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		/// <summary>
		/// 新增或修改信息
		/// </summary>
		public int AddOrUpdate(Sys_EnumCode model, UserSession sessionCurrent)
		{
			try
			{
				if (model == null)
				{
					throw new BuzException("参数不能为空");
				}
				if (model.PID == 0 && !string.IsNullOrEmpty(model.PCode))
				{
					model.PID = (from s in context.SysEnumCode
								 where s.Code == model.PCode && s.PID == 0
								 select s.ID).SingleOrDefault();
				}

				if (model.ID > 0)
				{
					if (model.PID == 0)
					{
						if (string.IsNullOrEmpty(model.Code))
						{
							throw new BuzException("参数编码不能为空");
						}
						if (context.SysEnumCode.Any(m => m.Code == model.Code && m.PID == model.PID && m.ID != model.ID))
						{
							throw new BuzException("参数编码已存在");
						}
					}
					if (context.SysEnumCode.Any(m => m.PID == model.PID && m.Name == model.Name && m.ID != model.ID))
					{
						throw new BuzException("参数已存在");
					}
					Update(model);
				}
				else
				{
					if (model.PID == 0)
					{
						if (string.IsNullOrEmpty(model.Code))
						{
							throw new BuzException("参数编码不能为空");
						}
						if (context.SysEnumCode.Any(m => m.Code == model.Code && m.PID == 0))
						{
							throw new BuzException("参数编码已存在");
						}
					}
					if (context.SysEnumCode.Any(m => m.PID == model.PID && m.Name == model.Name))
					{
						throw new BuzException("参数已存在");
					}
					model.AddDate = DateTime.Now;
					model.AddManID = sessionCurrent.UserID;
					model.AddManName = sessionCurrent.UserName;
					model.OrgID = sessionCurrent.OrgID;
					model.ID = Add(model);
				}
				return model.ID;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (DbUpdateException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("数据库保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取指定代码的参数信息（如果不存在该代码的参数则创建）
		/// </summary>
		/// <param name="code"></param>
		/// <param name="name"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public Sys_EnumCode EnsureCodeValid(string code, string name, UserSession sessionCurrent)
		{
			Sys_EnumCode model = null;
			try
			{
				if (string.IsNullOrEmpty(code))
				{
					throw new BuzException("参数不能为空");
				}

				model = context.SysEnumCode.SingleOrDefault(m => m.OrgID == sessionCurrent.OrgID && m.PID == 0 && m.Code == code);
				if (model == null)
				{
					model = new Sys_EnumCode()
					{
						AddDate = DateTime.Now,
						AddManID = sessionCurrent.UserID,
						AddManName = sessionCurrent.UserName,
						Code = code,
						Name = name,
						OrgID = sessionCurrent.OrgID,
					};
					Add(model);
				}
				return model;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (DbUpdateException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("数据库保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 批量更新
		/// </summary>
		/// <param name="models"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool BatchUpdate(IEnumerable<Sys_EnumCode> models, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				if (models == null)
				{
					throw new BuzException("参数不能为空");
				}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户未登录或登录已过期");
				}
				DateTime dtNow = DateTime.Now;
				string ip = GetRequestIP();

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						foreach (var p in models)
						{
							if (p == null)
							{
								throw new ArgumentException("参数不能为空");
							}
							if (p.ID > 0)
							{
								Update(p);
							}
							else
							{
								var codes = GetList(p.Code, sessionCurrent);
								if (codes == null || codes.Count == 0)
								{
									var code = new Sys_EnumCode();
									code.Code = p.Code;
									code.Value = p.Value;
									code.AddDate = dtNow;
									code.AddManID = sessionCurrent.UserID;
									code.AddManName = sessionCurrent.UserName;
									code.Comment = p.Comment;
									code.Reserved = p.Reserved;
									Add(code);

									serviceSysLog.Add(sessionCurrent, ip, "新增系统参数：" + p.Code + "->" + p.Value, dtNow);
								}
								else
								{
									if (codes[0].Value != p.Value)
									{
										serviceSysLog.Add(sessionCurrent, ip, "修改系统参数：" + p.Code + "->旧值（" + codes[0].Value + "），新值（" + p.Value + "）", dtNow);

										p.ID = codes[0].ID;
										p.Value = p.Value;
										Update(p);
									}
								}
							}
						}
						#endregion
						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}
				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存参数信息出错");
				throw new BuzException("保存参数信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 删除参数
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						if (context.SysEnumCode.Any(m => m.PID == id))
						{
							throw new BuzException("该类别下有下级类别，请先删除下级类别后再删除");
						}
						var modelOld = Get(id, true);
						Delete(modelOld);

						serviceSysLog.Add(sessionCurrent, ip, $"删除分类{modelOld.Name}[{modelOld.Code}]信息，原信息：", modelOld, dtNow);
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除分类出错");
				throw new BuzException("删除分类失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 根据id获取详细信息
		/// </summary>
		public Sys_EnumCode GetViewDetail(int id, UserSession sessionCurrent)
		{
			try
			{
				var query = from c in context.SysEnumCode
							join p in context.SysEnumCode on c.PID equals p.ID into all
							from a in all.DefaultIfEmpty()
							where c.ID == id
							select new Sys_EnumCode()
							{
								ID = c.ID,
								AddDate = c.AddDate,
								AddManID = c.AddManID,
								AddManName = c.AddManName,
								Comment = c.Comment,
								Value = c.Value,
								Code = c.Code,
								Name = c.Name,
								OrgID = c.OrgID,
								PID = c.PID,
								PName = a.Name,
								Reserved = c.Reserved,
								Sort = c.Sort
							};
				var model = query.SingleOrDefault();
				return model;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取信息出错");
				throw new BuzException("获取信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		public Sys_EnumCode GetEditDetail(int id, UserSession sessionCurrent)
		{
			try
			{
				var query = from c in context.SysEnumCode
							join p in context.SysEnumCode on c.PID equals p.ID into all
							from a in all.DefaultIfEmpty()
							where c.ID == id
							select new Sys_EnumCode()
							{
								ID = c.ID,
								AddDate = c.AddDate,
								AddManID = c.AddManID,
								AddManName = c.AddManName,
								Comment = c.Comment,
								Value = c.Value,
								Code = c.Code,
								Name = c.Name,
								OrgID = c.OrgID,
								PID = c.PID,
								PName = a.Name,
								Reserved = c.Reserved,
								Sort = c.Sort
							};
				var model = query.SingleOrDefault();
				return model;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取信息出错");
				throw new BuzException("获取信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}
	}
}